#!/usr/bin/python
# -*- coding: utf-8 -*-
import omen.engine.core.services as serv
import omen.tools.configuration as config
import omen.tools.omen_tools as file_tools
import os

class FolderSlotParamKeys(object):
    KEY_FOLDER_PATH = 'file_path'

## FolderInputSlot is an input slot based on the file system.
# Folder InputSlot reads files from a folder.
class FolderInputSlot(serv.InputSlot):
    def __init__(self, slot_name, conf):
        super(FolderInputSlot, self).__init__(slot_name)
        self._conf = None
        try:
            config.ConfigurationChecker.check_keys(conf, [FolderSlotParamKeys.KEY_FOLDER_PATH])
            self._conf = conf
        except config.ConfigurationCheckerError as err:
            raise serv.ServiceInitError, err
        

    def get_objects(self):
        result = []
        try:
            folder = self._conf[FolderSlotParamKeys.KEY_FOLDER_PATH]
            for a_file in os.listdir(folder):
                a_file_path = folder + os.sep + a_file
                if os.path.isfile(a_file_path):
                    text = file_tools.FileTools.read_text(a_file_path)
                    result.append((a_file, text))
        except RuntimeError, err:
            raise serv.SlotGetError('Error in get_objects: %s' % (str(err)))
                
        return result
    
    def delete_object(self, object_id):
        try:
            folder = self._conf[FolderSlotParamKeys.KEY_FOLDER_PATH]
            file_path = folder + '/' + object_id
            file_tools.FileTools.delete_file(file_path)
        except RuntimeError, err:
            raise serv.SlotDeleteError('Error in delete_object: %s' % (str(err)))
        
    def get_object(self, object_id):
        result = []
        try:
            folder = self._conf[FolderSlotParamKeys.KEY_FOLDER_PATH]
            a_file_path = folder + os.sep + object_id
            if os.path.isfile(a_file_path):
                text = file_tools.FileTools.read_text(a_file_path)
                result.append((object_id, text))
            else:
                raise RuntimeError('invalid object id (%s)' % (object_id))
        except RuntimeError, err:
            raise serv.SlotGetError('Error in get_object: %s' % (str(err)))
        
        return result
    
    
class FolderOutputSlot(serv.OutputSlot):
    def __init__(self, slot_name, conf):
        super(FolderOutputSlot, self).__init__(slot_name)
        self._conf = None
        try:
            config.ConfigurationChecker.check_keys(conf, [FolderSlotParamKeys.KEY_FOLDER_PATH])
            self._conf = conf
        except config.ConfigurationCheckerError as err:
            raise serv.ServiceInitError, err
